/**
 * 列表
 */
const Mock = require('mockjs')
const Random = Mock.Random

const genList = (current, pageSize) => {
  const tableListDataSource = []

  for (let i = 0; i < pageSize; i += 1) {
    const index = (current - 1) * 10 + i
    tableListDataSource.push({
      id: index,
      src: 'http://localhost:3003/assets/hero-card.jpeg',
      title: Random.csentence(),
      price: Random.float(60, 1000, 2, 2),
      vipPrice: Random.float(60, 1000, 2, 2),
      shopDescription: Random.cword(2, 4),
      delivery: Random.cword(2, 5),
      shopName: Random.cword(7, 14),
    })
  }
  return tableListDataSource
}

const tableListDataSource = genList(1, 100)

module.exports = (req, res) => {
  const data = req.body || {}
  const { current = 1, pageSize = 10 } = data
  let dataSource = [...tableListDataSource].slice(
    (current - 1) * pageSize,
    current * pageSize,
  )

  if (data.sorter) {
    const sorter = JSON.parse(data.sorter)
    dataSource = dataSource.sort((prev, next) => {
      let sortNumber = 0
      Object.keys(sorter).forEach((key) => {
        if (sorter[key] === 'descend') {
          if (prev[key] - next[key] > 0) {
            sortNumber += -1
          } else {
            sortNumber += 1
          }
          return
        }
        if (prev[key] - next[key] > 0) {
          sortNumber += 1
        } else {
          sortNumber += -1
        }
      })
      return sortNumber
    })
  }
  if (data.filter) {
    const filter = JSON.parse(data.filter)
    if (Object.keys(filter).length > 0) {
      dataSource = dataSource.filter((item) => {
        return Object.keys(filter).some((key) => {
          if (!filter[key]) {
            return true
          }
          if (filter[key].includes(`${item[key]}`)) {
            return true
          }
          return false
        })
      })
    }
  }

  if (data.name) {
    dataSource = dataSource.filter((data) =>
      data.name.includes(data.name || ''),
    )
  }

  let finalPageSize = 10
  if (data.pageSize) {
    finalPageSize = parseInt(`${data.pageSize}`, 10)
  }

  const result = {
    data: {
      list: dataSource,
      total: tableListDataSource.length,
      pageSize: finalPageSize,
      current: parseInt(`${data.current}`, 10) || 1,
    },
    code: '0',
    msg: '',
  }

  return result
}
